package edu.eas.admin.controller;

import cn.hutool.core.collection.CollUtil;
import edu.eas.admin.service.AdminService;
import edu.eas.admin.service.RoleService;
import edu.eas.common.api.CommonPage;
import edu.eas.common.api.CommonResult;
import edu.eas.common.constant.AuthConstant;
import edu.eas.common.constant.Constants;
import edu.eas.common.domain.UserDto;
import edu.eas.common.dto.AdminParam;
import edu.eas.common.dto.LoginParam;
import edu.eas.common.dto.MenuNode;
import edu.eas.common.pojo.Admin;
import edu.eas.common.pojo.Menu;
import edu.eas.common.pojo.Role;
import edu.eas.common.utils.ServletUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author cql
 */
@RestController
@Api(tags = "AdminController", description = "管理员管理")
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RoleService roleService;


    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @ApiOperation(value = "获取路由信息")
    @GetMapping("/getRouters")
    public CommonResult<List<MenuNode>> getRouters() {
        Admin admin = adminService.getCurrentAdmin();
        List<MenuNode> menuNodes = adminService.selectMenuTree(admin.getAdminId());
        return CommonResult.success(menuNodes);
    }

    @ApiOperation(value = "重置密码")
    @PutMapping("/resetPwd")
    public CommonResult resetPwd(@RequestBody Admin admin) {
        int count = adminService.resetPwd(admin);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }


    @ApiOperation(value = "删除用户(支持批量移除)")
    @DeleteMapping("{adminIds}")
    public CommonResult delete(@PathVariable("adminIds") Long[] adminIds) {
        int count = adminService.deleteAdminByIds(adminIds);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }


    @ApiOperation(value = "修改用户状态")
    @PutMapping("/changeStatus")
    public CommonResult changeStatus(@RequestBody Admin admin) {
        int count = adminService.changeStatus(admin);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }


    @ApiOperation(value = "获取用户详情")
    @GetMapping("{adminId}")
    public CommonResult<Map<String, Object>> getAdmin(@PathVariable("adminId") Long adminId) {
        // 1.获取用户基本信息
        Admin admin = adminService.getAdminByPrimaryKey(adminId);
        // 2.获取用户对应的角色
        List<Role> roleList = roleService.getRoleList(adminId, AuthConstant.USER_TYPE_ADMIN);
        List<Long> roleIds = roleList.stream().map(role -> role.getRoleId()).collect(Collectors.toList());

        Map<String, Object> data = new HashMap<>();
        data.put("admin", admin);
        data.put("roleIds", roleIds);
        data.put("roles", roleService.getAllRole());

        return CommonResult.success(data);
    }


    @ApiOperation(value = "新增管理员")
    @PostMapping
    public CommonResult create(@RequestBody AdminParam param) {
        int count = adminService.create(param);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }

    @ApiOperation(value = "新增管理员")
    @PutMapping("{adminId}")
    public CommonResult update(@PathVariable("adminId") Long adminId, @RequestBody AdminParam param) {
        int count = adminService.update(adminId, param);
        if (count > 0) {
            return CommonResult.success(count);
        } else {
            return CommonResult.failed();
        }
    }


    @ApiOperation(value = "获取基本信息,如角色列表,初始密码等")
    @GetMapping("/baseinfo")
    public CommonResult<Map<String, Object>> baseInfo() {
        Map<String, Object> map = new HashMap<>();

        // 初始密码
        map.put("initPassword", Constants.INIT_PASSWORD);
        // 角色
        List<Role> roles = roleService.getAllRole();
        map.put("roles", roles);
        return CommonResult.success(map);
    }


    @ApiOperation(value = "分页获取用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageSize", value = "每页大小", required = false),
            @ApiImplicitParam(name = "pageNum", value = "当前页码", required = false),
            @ApiImplicitParam(name = "username", value = "用户名称", required = false),
            @ApiImplicitParam(name = "status", value = "启用状态：0:禁用; 1:启用", required = false),
    })
    @GetMapping("/list")
    public CommonResult<CommonPage<Admin>> listUser(@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                                                    @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                    @RequestParam(value = "username", defaultValue = "") String username,
                                                    @RequestParam(value = "status", defaultValue = "-1") Integer status) {
        List<Admin> adminList = adminService.list(pageSize, pageNum, username, status);
        return CommonResult.success(CommonPage.restPage(adminList));
    }


    @ApiOperation(value = "登录以后返回token")
    @PostMapping(value = "/login")
    public CommonResult login(@Validated @RequestBody LoginParam loginParam) {
        return adminService.login(loginParam.getUsername(), loginParam.getPassword());
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping(value = "/info")
    public CommonResult getAdminInfo() {
        Admin admin = adminService.getCurrentAdmin();
        Map<String, Object> data = new HashMap<>();
        // 获取信息
        data.put("username", admin.getUsername());
        data.put("nickName", admin.getNickName());
        data.put("avatar", admin.getAvatar());
        // 角色信息
        List<Role> roleList = adminService.getRoleList(admin.getAdminId());
        if (CollUtil.isNotEmpty(roleList)) {
            List<String> roles = roleList.stream().map(Role::getRoleKey).collect(Collectors.toList());
            data.put("roles", roles);
        }
        return CommonResult.success(data);
    }

    @ApiOperation(value = "登出功能")
    @PostMapping(value = "/logout")
    @ResponseBody
    public CommonResult logout() {
        return CommonResult.success(null);
    }

    @ApiOperation("根据用户名获取通用用户信息")
    @GetMapping(value = "/loadByUsername")
    public UserDto loadUserByUsername(@RequestParam String username) {
        UserDto userDTO = adminService.loadUserByUsername(username);
        return userDTO;
    }

}
